package net.bac.sbe.web.sonar.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.bac.sbe.web.sonar.client.view.ReportView;
import net.bac.sbe.web.sonar.client.widgets.SbeListBox;
import net.bac.sbe.web.sonar.client.widgets.TextBoxWithPlaceholder;
import net.bac.sbe.web.sonar.shared.FieldVerifier;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class SbeSonarClient implements EntryPoint {
	private static final String SONAR_REPORT_ID = "sonarReport";

	private static final String ITEM_TO_RETAIN_REPORT_ID = "itemToRetainReport";

	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting
	 * service.
	 */
	private final ReportServiceAsync reportService = GWT
			.create(ReportService.class);

	private final ApplicationMaintenanceServiceAsync appMaintenanceService = GWT
			.create(ApplicationMaintenanceService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button sendButton = new Button("Generar Reportes");
		final TextBoxWithPlaceholder analystNameField = new TextBoxWithPlaceholder();
		final TextBoxWithPlaceholder projectBranchField = new TextBoxWithPlaceholder();
		final TextBoxWithPlaceholder projectNameField = new TextBoxWithPlaceholder();

		analystNameField.setPlaceholder("Nombre del Analista");
		projectBranchField.setPlaceholder("Codigo de branch");
		projectNameField.setPlaceholder("Nombre del proyecto");

		analystNameField.setWidth("15em");
		projectBranchField.setWidth("15em");
		projectNameField.setWidth("15em");

		// applications
		final Label errorLabel = new Label();

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("projectBranchContainer").add(projectBranchField);
		RootPanel.get("projectNameContainer").add(projectNameField);
		RootPanel.get("analystNameContainer").add(analystNameField);

		final SbeListBox multiBox = new SbeListBox(true);

		invokeAsynchronousApplicationsQuery(multiBox);

		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);
		RootPanel.get("applicationsContainer").add(multiBox);


		final VerticalPanel reportsVPanel = new VerticalPanel();

		CheckBox itemToRetainCheckBox = new CheckBox("Hoja de Pase");
		itemToRetainCheckBox.setName(ITEM_TO_RETAIN_REPORT_ID);
		CheckBox sonarCheckBox = new CheckBox("Reporte de Sonar");
		sonarCheckBox.setName(SONAR_REPORT_ID);


		final CheckBox compareAgainstBuildBranch = new CheckBox("Comparar contra el Branch de Integracion");
		compareAgainstBuildBranch.setName("compareAgainstBuildBranch");

		RootPanel.get("repositorySelectionContainer").add(compareAgainstBuildBranch);

		reportsVPanel.add(itemToRetainCheckBox);
		reportsVPanel.add(sonarCheckBox);

		RootPanel.get("reportsContainer").add(reportsVPanel);

		final DialogBox processDialogBox = new DialogBox();
		processDialogBox.setText("Generando reportes");
		processDialogBox.setAnimationEnabled(true);
		final VerticalPanel processDialogPanel = new VerticalPanel();
		processDialogPanel.addStyleName("dialogVPanel");
		processDialogPanel
		.add(new HTML(
				"<br><b>Por favor espere mientras se generan sus reportes</b>"));
		Image image = new Image("images/loading.gif");
		processDialogPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		processDialogPanel.add(image);
		processDialogBox.add(processDialogPanel);

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Reportes Generados");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final HTML serverResponseLabel = new HTML();

		final VerticalPanel dialogVPanel = new VerticalPanel();



		final VerticalPanel linksDialogPanel = new VerticalPanel();

		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel
				.add(new HTML(
						"<br><b>A continuacion los links a los reportes generados:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.add(linksDialogPanel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				generateReports();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					generateReports();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void generateReports() {



				errorLabel.setText("");
				String textToServer = analystNameField.getText();
				if (!FieldVerifier.isValidName(textToServer)) {
					errorLabel.setText("Please enter at least four characters");
					return;
				}

				// Then, we send the input to the server.
				sendButton.setEnabled(false);
				serverResponseLabel.setText("");

				processDialogBox.center();
				processDialogBox.show();

				List<String> reportsToGenerate = new ArrayList<String>();
				for (Iterator<Widget> iterator = reportsVPanel.iterator(); iterator
						.hasNext();) {
					CheckBox widget = (CheckBox)iterator.next();
					if(widget.getValue()){
						reportsToGenerate.add(widget.getName());
					}
				}


				invokeAsynchronousReportGeneration(analystNameField, projectNameField,
						projectBranchField, dialogBox, closeButton,
						serverResponseLabel, linksDialogPanel, reportsToGenerate, compareAgainstBuildBranch);
			}

			private void invokeAsynchronousReportGeneration(
					final TextBoxWithPlaceholder analystNameField,
					final TextBoxWithPlaceholder projectNameField,
					final TextBoxWithPlaceholder projectBranchField,
					final DialogBox dialogBox, final Button closeButton,
					final HTML serverResponseLabel,
					final VerticalPanel linksDialogPanel,
					final List<String> reportsToGenerate,
					final CheckBox compareAgainstBuildBranch) {

				String repository = "trunk";

				if (compareAgainstBuildBranch.getValue()){
					repository = "buildBranch";
				}

				reportService.generateProjectReports(
						projectBranchField.getText(),
						analystNameField.getText(),
						projectNameField.getText(),
						multiBox.getSelectedItems(),
						reportsToGenerate,
						repository,
						new AsyncCallback<List<ReportView>>() {
							public void onFailure(Throwable caught) {
								processDialogBox.hide();
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(List<ReportView> result) {
								processDialogBox.hide();
								dialogBox.setText("Generacion de reporte");
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");

								List<Widget> links = new ArrayList<Widget>();

								for (Widget widget : linksDialogPanel) {
									links.add(widget);
								}

								for (Widget widget2 : links) {
									linksDialogPanel.remove(widget2);
								}

								for (ReportView reportView : result) {
									Anchor link = new Anchor(
											reportView.getReportName(), reportView.getReportURLForDownload());
									link.setTarget("_blank");
									linksDialogPanel.add(link);
								}

								dialogBox.center();
								closeButton.setFocus(true);
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		analystNameField.addKeyUpHandler(handler);
	}


	private void invokeAsynchronousApplicationsQuery(final SbeListBox multiBox) {

		appMaintenanceService.getApplications(
				new AsyncCallback<List<String>>() {
					public void onFailure(Throwable caught) {
						//do nothing
					}

					public void onSuccess(List<String> result) {
						for (String app : result) {
							multiBox.addItem(app, app);
						}
						multiBox.setWidth("30em");
						multiBox.setVisibleItemCount(20);
					}
				});
	}
}
